package com.meilai.project.controller.web.adMake.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.controller.web.adMake.dto.BillAdMakeSearchParams;
import com.meilai.project.controller.web.adMake.entity.BillAdMakeMark;
import com.meilai.project.controller.web.adMake.mapper.BillAdMakeMarkMapper;
import com.meilai.project.controller.web.adMake.vo.BillAdMakeMarkVO;
import com.meilai.project.controller.web.adMake.vo.BillAdMakeWebVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 制作单-标记旧制作单 服务实现类
 * </p>
 *
 * @author 张驰
 * @since 2022-08-16
 */
@Service
public class BillAdMakeMarkServiceImpl extends ServiceImpl<BillAdMakeMarkMapper, BillAdMakeMark> implements BillAdMakeMarkService {
    @Autowired
    private BillAdMakeService billAdMakeService;

    @Transactional
    @Override
    public void deleteByAdMakeId(Long adMakeId) {
        LambdaQueryWrapper<BillAdMakeMark> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BillAdMakeMark::getBill_ad_make_id, adMakeId);
        remove(wrapper);
    }

    @Override
    public List<BillAdMakeWebVO> markVOListByAdMakeId(Long adMakeId) {
        List<BillAdMakeWebVO> result = new ArrayList<>();

        List<BillAdMakeMarkVO> marks = baseMapper.markVOListByAdMakeId(adMakeId);
        if(CollectionUtils.isNotEmpty(marks)){
            Map<Long, BillAdMakeMarkVO> markMap = marks.stream().collect(Collectors.toMap(BillAdMakeMarkVO::getMark_bill_ad_make_id, Function.identity(), (key1, key2) -> key2));
            Set<Long> markIds = marks.stream().map(BillAdMakeMarkVO::getMark_bill_ad_make_id).collect(Collectors.toSet());
            if(CollectionUtils.isNotEmpty(markIds)){
                BillAdMakeSearchParams searchParams = new BillAdMakeSearchParams();
                searchParams.setIds(new ArrayList<>(markIds));
                result = billAdMakeService.selectDataList(searchParams);
                result.forEach(d -> {
                    BillAdMakeMarkVO markVO = markMap.getOrDefault(d.getId(), null);
                    if(markVO != null) {
                        d.setMark_id(markVO.getMark_id());
                        d.setMark_name(markVO.getMark_name());
                        d.setMark_memo(markVO.getMark_memo());
                    }
                });
            }
        }

        return result;
    }
}
